#--*--coding=utf-8--*--
#MaterialCodeGenerator9.py
#

import chardet

import sys
from PySide6.QtWidgets import (QApplication, QWidget, QVBoxLayout, QHBoxLayout, 
                               QComboBox, QLineEdit, QPushButton, QLabel, QMessageBox, QCompleter)
from PySide6.QtCore import Qt
import json
import sqlite3

class MaterialCodeGenerator(QWidget):
    def __init__(self):
        super().__init__()
        
        self.initUI()
        #self.load_rules()
        #self.init_db()
    
    def initUI(self):
        self.layout = QVBoxLayout()
        
        # 初始化第一组下拉列表和搜索框
        self.add_group(0, 1)
        self.add_group(1, 2)
        self.add_group(2, 9)
        
        # 增加和删除按钮
        self.add_button = QPushButton("增加组")
        self.delete_button = QPushButton("删除组")
        self.generate_button = QPushButton("生成编码")
        self.copy_button = QPushButton("复制编码")
        
        button_layout = QHBoxLayout()
        button_layout.addWidget(self.add_button)
        button_layout.addWidget(self.delete_button)
        button_layout.addWidget(self.generate_button)
        button_layout.addWidget(self.copy_button)
        
        self.layout.addLayout(button_layout)
        
        # 结果标签
        self.result_label = QLabel("生成的编码: ")
        self.layout.addWidget(self.result_label)
        
        self.setLayout(self.layout)
        
        self.add_button.clicked.connect(self.add_group)
        self.delete_button.clicked.connect(self.delete_group)
        #self.generate_button.clicked.connect(self.generate_code)
        #self.copy_button.clicked.connect(self.copy_code)
    
    def add_group(self, index=None, length=1):
        if index is None:
            index = len(self.layout) - 1
        
        group_layout = QHBoxLayout()
        
        search_box = QLineEdit()
        combo_box = QComboBox()
        combo_box.setEditable(True)
        combo_box.setInsertPolicy(QComboBox.NoInsert)
        
        # 设置搜索功能
        completer = QCompleter()#self.get_options(index), self)
        completer.setCaseSensitivity(Qt.CaseInsensitive)
        completer.setFilterMode(Qt.MatchContains)
        completer.setCompletionMode(QCompleter.PopupCompletion)
        combo_box.setCompleter(completer)
        
        group_layout.addWidget(search_box)
        group_layout.addWidget(combo_box)
        
        self.layout.insertLayout(index, group_layout)
    
    def delete_group(self):
        if len(self.layout) > 4:
            item = self.layout.takeAt(len(self.layout) - 2)
            while item:
                widget = item.widget()
                if widget:
                    widget.deleteLater()
                item = self.layout.takeAt(len(self.layout) - 2)
"""    
    def generate_code(self):
        code_parts = []
        for i in range(3):
            combo_box = self.layout.itemAt(i).layout().itemAt(1).widget()
            code_parts.append(combo_box.currentText())
        
        code = '.'.join(code_parts)
        
        # 检查数据库中是否存在相同的编码
        if self.check_code_existence(code):
            QMessageBox.warning(self, "警告", "生成的编码已存在，请重新生成。")
            return
        
        # 更新最后四位
        last_part = self.update_last_part(code_parts[0] + code_parts[1] + code_parts[2])
        code += '.' + last_part
        
        self.result_label.setText(f"生成的编码: {code}")
        self.save_code_to_db(code)
    
    def copy_code(self):
        clipboard = QApplication.clipboard()
        clipboard.setText(self.result_label.text().split(': ')[1])
    
    def get_options(self, index):
        if index == 0:
            return [str(i) for i in range(10)] + [chr(i) for i in range(ord('a'), ord('z') + 1)]
        elif index == 1:
            return [f"{i}{j}" for i in range(10) for j in range(10)] + \
                   [f"{i}{j}" for i in range(ord('a'), ord('z') + 1) for j in range(ord('a'), ord('z') + 1)]
        else:
            return [f"{i}{j}{k}{l}{m}{n}{o}{p}{q}{r}" for i in range(10) for j in range(10) for k in range(10) for l in range(10) for m in range(10) for n in range(10) for o in range(10) for p in range(10) for q in range(10) for r in range(10)]
    
    def check_code_existence(self, code):
        conn = sqlite3.connect('material_codes.db')
        cursor = conn.cursor()
        cursor.execute("SELECT * FROM codes WHERE code=?", (code,))
        result = cursor.fetchone()
        conn.close()
        return result is not None
    
    def update_last_part(self, prefix):
        conn = sqlite3.connect('material_codes.db')
        cursor = conn.cursor()
        cursor.execute("SELECT MAX(last_part) FROM codes WHERE prefix=?", (prefix,))
        max_last_part = cursor.fetchone()[0]
        new_last_part = str(int(max_last_part) + 1) if max_last_part else '0001'
        conn.close()
        return new_last_part.zfill(4)
    
    def save_code_to_db(self, code):
        prefix, last_part = code.rsplit('.', 1)
        conn = sqlite3.connect('material_codes.db')
        cursor = conn.cursor()
        cursor.execute("INSERT INTO codes (code, prefix, last_part) VALUES (?, ?, ?)", (code, prefix, last_part))
        conn.commit()
        conn.close()
    
    def load_rules(self):
        try:
            with open('rules3.json', 'r') as f:
                self.rules = json.load(f)
        except FileNotFoundError:
            self.rules = {}
    
    def init_db(self):
        conn = sqlite3.connect('material_codes.db')
        cursor = conn.cursor()
        cursor.execute('''CREATE TABLE IF NOT EXISTS codes (
                          id INTEGER PRIMARY KEY AUTOINCREMENT,
                          code TEXT UNIQUE,
                          prefix TEXT,
                          last_part TEXT
                        )''')
        conn.commit()
        conn.close()
"""
if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = MaterialCodeGenerator()
    ex.show()
    sys.exit(app.exec())